package com.cxd.app.service;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.cxd.app.entity.AppBanner;
import com.cxd.app.entity.AppDataStatic;
import com.cxd.app.entity.base.AppLogBase;
import com.cxd.app.entity.base.BannerPictureBase;
import com.cxd.app.entity.base.DeviceTokenBase;
import com.cxd.app.entity.base.OpinionBase;
import com.cxd.app.mapper.read.ROtherMapper;
import com.cxd.app.mapper.write.WOtherMapper;
import com.cxd.base.common.constants.InvestConstants;
import com.cxd.base.common.exception.CxdException;
import com.cxd.base.page.PageUtil;
import com.cxd.base.page.tag.TagPage;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.MapUtil;
import com.cxd.base.util.NumberUtil;
import com.cxd.base.util.ParamUtil;
import com.cxd.base.util.SequenceManager;
import com.cxd.base.util.wtj.BUtils;
import com.cxd.message.exception.AppConstants;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2015年12月8日 下午4:48:40
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
@Service("otherService")
public class OtherService {
	@Resource
	public BeanTools bt;
	@Resource
	ROtherMapper rotherMapper;
	
	@Resource
	WOtherMapper wotherMapper;
	/**
	 * 统计就是怎么麻烦怎么***
	 * @author wtj
	 * @date 2016年3月2日上午9:03:38
	 * @param json
	 */
	
	// 总投资额满20亿时间
	public static final String FULL_TIME = "2016-03-03 10:00:00";
	// 最低保证金
	public static final String LOW_BZ_MONEY = "10000000.00";
	public void moneyStatic(JSONObject json){
		AppDataStatic data = new AppDataStatic();
		data.setTotalMoney(NumberUtil.getNumber(getAllInvestsMoney()));
		data.setTotalProfit(NumberUtil.getNumber(getAllInvestsInterest()));
		/**
		 * 风险保证金
		 * select sum(invest.investMoney) from Invest invest where invest.status not in ('wait_affirm',?)
		 */
		
		// 用户总投资额
		String sql = "SELECT lt.repay_time_unit as repayTimeUnit,sum(invest.money) investMoney FROM INVEST invest "
				+ "LEFT JOIN loan lo on invest.loan_id = lo.id  "
				+ "LEFT JOIN loan_type lt on lo.type = lt.id  "
				+ "WHERE invest.STATUS not in ('%s','%s') and invest.time > '%s' group by lt.repay_time_unit";
		List<Map<String,Object>> listMap = bt.queryListMap(String.format(sql, InvestConstants.InvestStatus.WAIT_AFFIRM,InvestConstants.InvestStatus.CANCEL,FULL_TIME));
		BigDecimal dayInvestMoney = new java.math.BigDecimal("0");
		BigDecimal monthInvestMoney = new java.math.BigDecimal("0");
		for(Map<String,Object> obj:listMap){
			if(obj.get("repayTimeUnit").equals("day")){
				dayInvestMoney = new java.math.BigDecimal(obj.get("investMoney").toString());
			}
			if(obj.get("repayTimeUnit").equals("month")){
				monthInvestMoney = new java.math.BigDecimal(obj.get("investMoney").toString());
			}
		}
		BigDecimal allGuaranteeMoney = new  BigDecimal(LOW_BZ_MONEY).add(new  BigDecimal(0.0005).multiply(monthInvestMoney)).add(new  BigDecimal(0.0001).multiply(dayInvestMoney));
		data.setGuaranteeMoney(NumberFormat.getCurrencyInstance().format(allGuaranteeMoney.setScale(0, BigDecimal.ROUND_HALF_UP)).replace("$", "").replace("￥", "").replace(".00", ""));
		data.setFailBill("0");
		data.setOverdueBill("0");
		json.put("result", data);
	};
	
	/**
	 * 计算在平台上所有用户已经投资成功的总的金额
	 * 
	 * @return
	 */
	public double getAllInvestsMoney() {
		String sql = "select sum(invest_money) countNum from Invest invest where status not in ('"+InvestConstants.InvestStatus.WAIT_AFFIRM+"','"+InvestConstants.InvestStatus.CANCEL+"') ";
		Map<String,Object> map = bt.queryMap(sql);
		if (map == null) {
			return 0;
		}
		return (Double) map.get("countNum");
	}
	
	/**
	 * 计算在平台上所有用户已经投资成功的总的收益
	 * 
	 * @return
	 */
	private double getAllInvestsInterest() {
		String sql = "SELECT sum(INTEREST+DEFAULT_INTEREST-FEE) countNum FROM INVEST_REPAY WHERE TIME is not null ";
		Map<String,Object> map = bt.queryMap(sql);
		if (map == null) {
			return 0;
		}
		return (Double) map.get("countNum");
	}
	
	/**
	 * 加载APP banner
	 * @author wtj
	 * @date 2015年12月9日下午8:25:09
	 * @param json
	 * @return
	 */
	public JSONObject loadBanners(JSONObject json){
//		List<Map<String,Object>> listBean = bt.queryListMap("SELECT * FROM BANNER_PICTURE WHERE BANNER_ID='index_mobile'");
		List<Map<String,Object>> listMap = rotherMapper.loadBanners();
		List<BannerPictureBase> listBean = BUtils.tableListMapToBean(listMap, BannerPictureBase.class);
		if(listBean==null||listBean.size()==0){
			json.put("500", "暂无banner图片上传");
			json.put("status", "暂无banner图片上传");
		}else{
			List<AppBanner> lb = new ArrayList<AppBanner>();
			for(BannerPictureBase bean :listBean){
				AppBanner ab = new AppBanner();
				ab.setLocation(bean.getPicture());
				ab.setUrl(bean.getUrl());
				ab.setImgRootUrl(AppConstants.PublicConstants.IMG_ROOT_URL);
				ab.setTitle(bean.getTitle());
				lb.add(ab);
			}
			json.put("result",lb);
		}
		return json;
	}
	
	/**
	 * 意见反馈
	 * @author wtj
	 * @date 2015年12月9日下午8:25:36
	 * @param json
	 * @return
	 */
	public JSONObject feedback(JSONObject json,String value){
		Map<String, String> param = MapUtil.jsonToMapString(value);
		String userId = param.get("userId");
		String content = param.get("content");
		String email = param.get("email");
		ParamUtil.notNullParam("反馈内容:"+content);
//		if(!checkEmail(email)){
//			json.put("status", 500);
//			json.put("msg", "邮箱格式不正确");
//		}else{
		OpinionBase opinion = new OpinionBase();
		opinion.setContent(content);
		opinion.setEmail(email);
		opinion.setTime(new Date());
		opinion.setUserId(userId);
		bt.add(opinion);
//		}
		json.put("result", new String[]{});
		return json;
	}
	
	/**
	 * @author wtj
	 * @date 2015年12月9日下午8:52:19
	 * @param email
	 * @return
	 */
	@SuppressWarnings("unused")
	private boolean checkEmail(String email){
		String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern p = Pattern.compile(check);
		Matcher m = p.matcher(email);
		return m.matches();
	}
	
	/**
	 * 最新公告
	 * @author wtj
	 * @date 2015年12月16日上午10:19:24
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject loadNews(JSONObject json,String value){
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object pageSize = param.get("pageSize");
		Object currentPage = param.get("currentPage");
		if(pageSize==null||currentPage==null){
			throw new CxdException("分页信息不能为空");
		}
		TagPage page =  PageUtil.getTagPage(currentPage.toString(), pageSize.toString());
		param.put("page", page);
		List<Map<String,Object>> listNode = rotherMapper.loadNewsListPage(param);
		Map<String,Object> nodeMap = new HashMap<String,Object>();
		for(Map<String,Object> m:listNode){
			m.put("imgRoot",  AppConstants.PublicConstants.IMG_ROOT_URL);
		}
		nodeMap.put("map", listNode);
		nodeMap.put("imgRoot",AppConstants.PublicConstants.IMG_ROOT_URL);
		json.put("result", nodeMap);
		return json;
	}	

	/**
	 * 新的获取最新公告
	 * @author wtj
	 * @date 2016年3月9日下午3:52:12
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject loadNewNoticeList(JSONObject json,String value){
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object pageSize = param.get("pageSize");
		Object currentPage = param.get("currentPage");
		if(pageSize==null||currentPage==null){
			throw new CxdException("分页信息不能为空");
		}
		TagPage page =  PageUtil.getTagPage(currentPage.toString(), pageSize.toString());
		param.put("page", page);
		List<Map<String,Object>> listNode = rotherMapper.loadNewNoticeListPage(param);
		json.put("result", listNode);
		return json;
	}
	
	/**
	 * 获取通知详情
	 * @author wtj
	 * @date 2016年3月14日下午3:19:30
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject loadNoticeDetail(JSONObject json,String value){
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object noticeId = param.get("noticeId");
		if(noticeId==null){
			throw new CxdException("通知ID不能为空");
		}
		List<Map<String,Object>> listNode = rotherMapper.loadNoticeDetail(param);
		json.put("result", listNode);
		return json;
	}
	
	/**
	 * 获取还款通知
	 * @author wtj
	 * @date 2016年3月9日下午3:52:12
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject loadRepayList(JSONObject json,String value){
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object pageSize = param.get("pageSize");
		Object currentPage = param.get("currentPage");
		if(pageSize==null||currentPage==null){
			throw new CxdException("分页信息不能为空");
		}
		TagPage page =  PageUtil.getTagPage(currentPage.toString(), pageSize.toString());
		param.put("page", page);
		List<Map<String,Object>> listNode = rotherMapper.loadRepayListPage(param);
		json.put("result", listNode);
		return json;
	}
	
	/**
	 * 检查是否有新公告
	 * @author wtj
	 * @date 2016年3月10日上午11:51:12
	 * @param json
	 * @param value
	 * @return
	 */
//	public JSONObject checkNewNotice(JSONObject json,String value){
//		Map<String, Object> param = MapUtil.jsonToMap(value);
//		Object maxTime = param.get("maxTime");
//		Object minTime = param.get("minTime");
//		Object  size = param.get("2");
//		param.put("maxTime",maxTime);
//		param.put("minTime", minTime);
//		param.put("size", size);
//		List<Map<String,Object>> listNode = rotherMapper.loadNewNoticeList(param);
//		Map<String,Object> mm = new HashMap<String,Object>();
//		if(listNode!=null && listNode.size()>0){
//			mm.put("isExist", true);
//		}else{
//			mm.put("isExist", false);
//		}
//		json.put("result", mm);
//		return json;
//	}
	/**
	 * 检查是否有新公告
	 * @author wtj
	 * @date 2016年3月10日上午11:51:12
	 * @param json
	 * @param value
	 * @return
	 */
	public JSONObject uploadDeviceToken(JSONObject json,String value){
		Map<String, Object> param = MapUtil.jsonToMap(value);
		Object deviceToken = param.get("deviceToken");
		Object userId = param.get("userId");
		ParamUtil.notNullParam("手机标识:" + deviceToken, "用户ID:" + userId);
		List<Map<String,Object>> li = bt.queryListMap(String.format("select id from device_token where user_id='%s' and device_token='%s'", userId.toString().trim(),deviceToken.toString().trim()));
		Map<String,Object> mm = new HashMap<String,Object>();
		if(li==null || li.size()==0){
			DeviceTokenBase dt = new DeviceTokenBase();
			dt.setId(SequenceManager.getNextId());
			dt.setCtime(new Date());
			dt.setDeviceToken(deviceToken.toString());
			dt.setUserId(userId.toString());
			bt.add(dt);
			mm.put("isSuccess", true);
		}else{
			mm.put("isSuccess", true);
		}
		json.put("result", mm);
		return json;
	}
	
	// 记录app log日志
	public JSONObject appLog(JSONObject json,String value){
		AppLogBase appLog = new AppLogBase();
		appLog.setCtime(new Date());
		appLog.setData(value);
		appLog.setId(SequenceManager.getNextId());
		wotherMapper.appLog(appLog);
		return json;
	}
}
